package com.wn.ziroom.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.wn.utils.CookieUtils;
import com.wn.utils.JwtUtils;
import com.wn.ziroom.entity.*;
import com.wn.ziroom.service.*;
import com.wn.ziroom.utils.JsonUtils;
import com.wn.ziroom.vo.RentHouseVo;
import com.wn.ziroom.vo.RoomUo;
import com.wn.ziroom.vo.SignVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Controller
public class PayController {

    @Autowired
    private UserService userService;
    private QuartersService quartersService;
    private OwnerService ownerService;
    private AlipayClient alipayClient;

    private StringRedisTemplate redisTemplate;
    private RoomService roomService;
    private IncomeorderService incomeorderService;
    private CartService cartService;

    @Autowired
    public void setCartService(CartService cartService) {
        this.cartService = cartService;
    }

    //----------------------------------------------------------------------------------------
    private AlipayTradePagePayRequest alipayRequest;

    private AlipayTradePagePayRequest alipayProductionRequest;

    @Autowired
    @Qualifier("alipayProductionRequest")
    public void setAlipayProductionRequest(AlipayTradePagePayRequest alipayProductionRequest) {
        this.alipayProductionRequest = alipayProductionRequest;
    }
    //---------------------------------------------------------------------------------------------

    @Autowired
    public void setIncomeorderService(IncomeorderService incomeorderService) {
        this.incomeorderService = incomeorderService;
    }

    @Autowired
    public void setQuartersService(QuartersService quartersService) {
        this.quartersService = quartersService;
    }

    @Autowired
    public void setOwnerService(OwnerService ownerService) {
        this.ownerService = ownerService;
    }

    @Autowired
    public void setRoomService(RoomService roomService) {
        this.roomService = roomService;
    }

    @Autowired
    public void setAlipayClient(AlipayClient alipayClient) {
        this.alipayClient = alipayClient;
    }


    @Autowired
    @Qualifier("alipayRequest")
    public void setAlipayTradePagePayRequest(AlipayTradePagePayRequest alipayRequest) {
        this.alipayRequest = alipayRequest;
    }

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    private OrderService orderService;

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * @param out_trade_no 商户订单号，商户网站订单系统中唯一订单号，必填
     * @param total_amount 付款金额，必填
     * @param subject      订单名称，必填
     * @param body         商品描述，可空
     * @return
     */
    @RequestMapping("/payHouse")
    @ResponseBody
    public String detailPayRequest(
            @RequestParam("WIDout_trade_no") String out_trade_no,
            @RequestParam("WIDtotal_amount") String total_amount,
            @RequestParam("WIDsubject") String subject,
            @RequestParam("WIDbody") String body,
            HttpServletRequest request) {

        //-- 删除已有的key


        //-- 2.请求支付宝 支付
        try {
            //获得初始化的AlipayClient
            //AlipayClient alipayClient = new DefaultAlipayClient(AlipayProperties.gatewayUrl, AlipayProperties.app_id, AlipayProperties.merchant_private_key, "json", AlipayProperties.charset, AlipayProperties.alipay_public_key, AlipayProperties.sign_type);

            //设置请求参数
            //AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            //alipayRequest.setReturnUrl(AlipayProperties.return_url);
            //alipayRequest.setNotifyUrl(AlipayProperties.notify_url);

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
            redisTemplate.opsForValue().set("类型",subject);
            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(result);

            //输出
            return result;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/payRenewal")
    @ResponseBody
    public String detailPayRenewal(
            @RequestParam("WIDout_trade_no") String out_trade_no,
            @RequestParam("WIDtotal_amount") String total_amount,
            @RequestParam("WIDsubject") String subject,
            @RequestParam("WIDbody") String body,
            HttpServletRequest request) {

        try {
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            redisTemplate.opsForValue().set("类型",subject);
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(result);

            return result;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }


    @RequestMapping("/goToPayRenting")
    @ResponseBody
    public String detailPayRenting(
            @RequestParam("WIDout_trade_no") String out_trade_no,
            @RequestParam("WIDtotal_amount") String total_amount,
            @RequestParam("WIDsubject") String subject,
            @RequestParam("WIDbody") String body,
            HttpServletRequest request) {

        try {
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            redisTemplate.opsForValue().set("类型",subject);
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(result);

            return result;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }
    @GetMapping("/goToReturn")
    public String goToReturn(HttpServletRequest request) {
        String type = redisTemplate.opsForValue().get("类型");
        /*---------------房屋托管----------------*/
        if ("自如".equals(type)){

            String token = CookieUtils.getCookie("token", request);
            Owner owner = JwtUtils.verifyTokenWithoutVerifyExp(token, Owner.class);
            owner = ownerService.selectByPhoneNumber(owner.getPhone());
            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
            String s = opsForValue.get(owner.getPhone() + "rentHouseVo");
            RentHouseVo rentHouseVo = JsonUtils.toObject(s, RentHouseVo.class);
            SignVo signVo = JsonUtils.toObject(opsForValue.get(owner.getPhone() + "signVo"), SignVo.class);
            /*--------------------生成房源信息*/


            Room room = new Room();
            room.setRent(rentHouseVo.getZiroomPrice());
            room.setType("1");
            room.setOwnerId(owner.getId());
            room.setNumber(String.valueOf(signVo.getHouserid()));
            room.setQuartersId(quartersService.selectByQname(rentHouseVo.getQuartername()).getId());
            room.setStartTime(owner.getSigningTime());
            room.setEndTime(owner.getExpirationTime());
            room.setArea(rentHouseVo.getArea());
            room.setBuild(signVo.getBuild());
            String roomType = "";
            if (rentHouseVo.getRoomtype().equals("1")) {
                roomType = "一室一厅";
            }
            if (rentHouseVo.getRoomtype().equals("1")) {
                roomType = "一室二厅";
            }
            if (rentHouseVo.getRoomtype().equals("1")) {
                roomType = "二室一厅";
            }
            if (rentHouseVo.getRoomtype().equals("1")) {
                roomType = "二室二厅";
            }
            room.setRoomtype(roomType);
            Room newRoom = roomService.add(room);


            /*--------------------生成付款计划*/
            Date signingTime = owner.getSigningTime();
            long starttime = signingTime.getTime();
            Date expirationTime = owner.getExpirationTime();
            long endtime = expirationTime.getTime();
            long month = 2592000000L;
            while (starttime < endtime) {
                new Date(starttime);
                Incomeorder incomeorder = new Incomeorder();
                incomeorder.setOwnerId(owner.getId());
                incomeorder.setRent(rentHouseVo.getZiroomPrice());
                incomeorder.setAddressId(newRoom.getId());
                incomeorder.setStatus(0);
                incomeorder.setStartTime(new Date(starttime));
                incomeorder.setEndTime(new Date(starttime + month));
                incomeorderService.add(incomeorder);
                starttime += month;
            }
                /*-----------删除多余redis----------*/
            redisTemplate.delete("类型");
            redisTemplate.delete(owner.getPhone() + "rentHouseVo");
            redisTemplate.delete(owner.getPhone() + "signVo");
            return "redirect:/ziroom_portal/owner/goToIncome";
        }
        else if ("续约".equals(type)){
            String token = CookieUtils.getCookie("token", request);
            User user = JwtUtils.verifyTokenWithoutVerifyExp(token, User.class);
            user = userService.selectByPhoneNumber(user.getPhone());
            long l = user.getEndtime().getTime() + 31536000000L;
            Date date = new Date(l);
            user.setEndtime(date);
            userService.updateById(user);
            redisTemplate.delete("类型");
            return "redirect:/ziroom_portal/user/goTouserInfo";

        }
        else if ("退租".equals(type)){
            String token = CookieUtils.getCookie("token", request);
            User user = JwtUtils.verifyTokenWithoutVerifyExp(token, User.class);
            user = userService.selectByPhoneNumber(user.getPhone());
            user.setEndtime(new Date());
            user.setStarttime(new Date());
            userService.updateById(user);
            Room room=roomService.selectByUserId(user.getId());
            room.setUserId(0);
            roomService.updateById(room);

            redisTemplate.delete("类型");

            return "redirect:/ziroom_portal/user/goTouserInfo";

        }

        String token2 = CookieUtils.getCookie("token", request);
        User user = JwtUtils.verifyTokenWithoutVerifyExp(token2, User.class);
        Integer userId = user.getId();

        ValueOperations<String, String> forValue = redisTemplate.opsForValue();
        String key = "userProduction" + userId;
        String s1 = forValue.get(key);
        String substring = s1.substring(0, 4);

        if (substring.equals("商品购物")) {

            //-- 删除redis中
            redisTemplate.delete(key);
            //-- 修改订单状态
            String productionOrderNumber = s1.substring(4);
            orderService.changeProductionStateToTwo(productionOrderNumber);

            //-- 删除redis中 购物车商品
            Order order = orderService.findOrderByOrderNumber(productionOrderNumber);
            String productionId = order.getProductionId();
            String[] splitProductionId = productionId.split(",");

            cartService.deleteByProductionIds(splitProductionId,userId);

            return "redirect:/ziroom_portal/production/productionList";
        }
        return "index";
    }


    @ResponseBody
    @RequestMapping("/payProduction")
    public String payProduction(@RequestParam("detail") String detail,
                                HttpServletRequest request) {

        String[] allDetail = detail.split(",");

        //-- 订单号
        String[] order = allDetail[0].split(":");
        String out_trade_no = "商品购物" + order[1];

        //-- 总价
        String total_amount = allDetail[1].split(":")[1];

        String subject = allDetail[2].split(":")[1];

        String body = "购买商品Id:" + allDetail[2].split(":")[1];

        //-- 2.请求支付宝 支付
        try {
            //获得初始化的AlipayClient
            //AlipayClient alipayClient = new DefaultAlipayClient(AlipayProperties.gatewayUrl, AlipayProperties.app_id, AlipayProperties.merchant_private_key, "json", AlipayProperties.charset, AlipayProperties.alipay_public_key, AlipayProperties.sign_type);

            //设置请求参数
            //AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            //alipayRequest.setReturnUrl(AlipayProperties.return_url);
            //alipayRequest.setNotifyUrl(AlipayProperties.notify_url);

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(result);

            // 保存到redis
            String token = CookieUtils.getCookie("token", request);
            User user = JwtUtils.verifyTokenWithoutVerifyExp(token, User.class);
            Integer userId = user.getId();

            ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();

            String key = "userProduction" + userId;
            opsForValue.set(key, out_trade_no);

            // 发送到队列
            orderService.sendOrderNumberToQueue(out_trade_no);

            //输出
            return result;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }

   /* @GetMapping("/goToProductionReturn")
    public String goToProductionReturn(){
        return "returnText";
    }*/
}
